<template>
	<view :class="['qn-page-' + theme]" class="view-wrap" :style="pageStyle">
		<NavigationBar v-if="is_data" :scrollTop="scrollTop" :modelData="topData" @switchStore="switchStore" />
		<view style="position: relative; z-index: 2;">
			<block v-if="is_data">
				<!-- 装修组件 -->
				<PageDesign :temData="temData" :showGoodsPrice="showGoodsPrice" :selAddress="now_sel_address">
				</PageDesign>
			</block>
			<!-- 骨架 -->
			<Skeleton v-else :imgTitle="true" :loading="true" :showAvatar="false"></Skeleton>
			<!-- #ifdef APP-PLUS -->
			<u-popup v-model="upgradePop" mode="center" :border-radius="12">
				<view class="upgrade-view">
					<image class="upgrade-img" :src="imgHost + '/statics/shengji.jpg'" mode="aspectFit"></image>
					<view class="upgrade-tit">发现新版本</view>
					<view class="upgrade-num">{{ newVersion }}</view>
					<view class="upgrade-cont">
						为了您更好的体验，
						<br />
						请您去升级到新版本哦！
					</view>
					<view @click="downloadApp" class="upgrade-btn">立即升级</view>
					<view class="closePop" @click="closeUPop"><text class="ibonfont ibonguanbi"></text></view>
				</view>
			</u-popup>
			<u-popup :mask-close-able="false" v-model="up_show" mode="center" :border-radius="12">
				<view class="upgrade-view">
					<image class="upgrade-img" :src="imgHost + '/statics/shengji.jpg'" mode="aspectFit"></image>
					<view class="upgrade-tit">新版本更新中</view>
					<view class="upgrade-cont"><u-line-progress :striped="true" :percent="up_percent"
							:striped-active="true"></u-line-progress></view>
				</view>
			</u-popup>
			<!-- #endif -->
			<u-modal v-model="tip_model" @confirm="finishCofirm" @cancel="tipCancel" :show-cancel-button="true"
				content="请先完善资料,再进行购物" confirm-text="去完善" cancel-text="逛逛商城"></u-modal>
			<!-- 底部tabbar -->
			<Tabbar v-model="current"></Tabbar>
		</view>
	</view>
</template>
<script>
import permision from '@/access/wa-permission/permission.js';
import PageDesign from '@/components/PageDesign/PageDesign.vue';
import { getToken, getUserInfo } from '@/access/common.js';
import NavigationBar from '@/components/PageDesign/components/NavigationBar.vue';
import Skeleton from '@/components/J-skeleton.vue';
import webUrl from '@/config.js';
export default {
	components: {
		PageDesign,
		Skeleton,
		NavigationBar
	},
	data() {
		return {
			imgHost : webUrl.QN_URL,
			tip_model: false, // 完善资料提示
			up_percent: 0,
			up_show: false,
			current: 0,
			upgradePop: false,
			newVersion: '',
			oldVersion: 'v1.0.6',
			model: 0,
			now_sel_address: {},
			home_data: {},
			temData: {},
			is_data: false,
			show_goods_price: 4,
			userCenterId: '',
			topData: {
				name: '',
				topBgColor: '#ffffff',
				textColor: '#000000',
				pageBgColor: '#f7f8fa',
				bgImage: ''
			},
			startUpPage: {
				img: '',
				isEnable: false,
				time: 5
			},
			scrollTop: 0
		};
	},
	computed: {
		enterprice() {
			return this.$store.state.enterpriseInfo;
		},
		isUpdate() {
			return this.$store.state.isUpdate;
		},
		pageTit() {
			if (this.temData.length) {
				const obj = this.temData[0].modelData;
				return obj.name;
			} else {
				return this.baseSet.shop || '首页';
			}
		},
		baseSet() {
			return this.$store.state.baseSet;
		},
		pageStyle() {
			if (this.temData.length) {
				const obj = this.temData[0].modelData;
				return `background-color:${obj.pageBgColor};background-image:url(${obj.bgImage});backgroundPosition: ${obj.topBgColor ? '0 ' + (this.barHeight + 44) + 'px' : '0 0'
					}`;
			} else {
				return '';
			}
		},
		isLogin() {
			return this.$store.state.hasLogin;
		},
		showGoodsPrice() {
			if (this.baseSet.goodsPrice === 5 && this.isLogin) {
				return '';
			} else if (!this.isLogin && this.baseSet.goodsPrice === 4) {
				return '请登录';
			} else if (this.$store.state.userStatus.enableStatus === 4 && this.baseSet.goodsPrice === 4) {
				return '已禁用';
			} else if (this.$store.state.userStatus.status !== 2 && this.baseSet.goodsPrice === 4) {
				if (this.$store.state.userStatus.status === 0) {
					return '待审核';
				} else if (this.$store.state.userStatus.status === 1) {
					return '审核中';
				} else if (this.$store.state.userStatus.status === 3) {
					return '已驳回';
				}
			} else {
				return '';
			}
		},
		// #ifdef APP-PLUS
		iosAuditStatus() {
			return this.$store.state.iosAuditStatus;
		}
		// #endif
	},
	watch: {
		'$store.state.locationObj'(val) {
			if (JSON.stringify(val) === '{}') {
				console.log(333);
				this.getAuthorizeInfo();
				return;
			}
			uni.hideToast();
			this.getTemplate();
		},
		isLogin(val) {
			this.getTemplate();
			this.getIndexData();
		}
	},
	async onShow() {
		console.log('aaaaaa',uni.getExtConfigSync());
		// #ifdef APP-PLUS
		if (JSON.stringify(this.$store.state.locationObj || {}) === '{}') {
			if (plus.os.name == 'iOS') {
				let result = permision.judgeIosPermission('location');
				if (result) {
					await this.resetGetLocation();
				}
			} else {
				let result = await permision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION');
				if (result == 1) {
					await this.resetGetLocation();
				}
			}
		}
		// #endif
		// #ifdef MP-WEIXIN || MP-TOUTIAO || H5
		console.log(JSON.stringify(this.$store.state.locationObj))
		if (JSON.stringify(this.$store.state.locationObj || {}) === '{}') {
			await this.getAuthorizeInfo();
			return;
		}
		// #endif
	},
	// 发送给朋友
	onShareAppMessage() {
		return {
			title: this.baseSet.shop,
			path: '/pages/index/index?businessmanId=' + (this.$store.state.userStatus.id || ''),
			success: res => {
				console.log(res);
			}
		};
	},
	// #ifdef MP-WEIXIN
	// 分享到朋友圈
	onShareTimeline(obj) { },
	// 收藏小程序
	onAddToFavorites() { },
	// #endif
	async onLoad(options) {
		//await this.getLocation();		
		await this.getTemplate();
		await this.getEnterpriseInfo();
		// #ifdef MP
		//  获取小程序分销商参数
		if (options.businessmanId) {
			this.$store.commit('commit_businessmanId', options.businessmanId);
			this.relationshipBusinessman(options.businessmanId);
		} else if (options.scene) {
			// 扫码进入
			const scene = decodeURIComponent(options.scene);
			if (scene.indexOf('_') > -1) {
				const id = scene.slice(0, scene.length - 1);
				console.log('staffId', id);
				this.$store.commit('commit_staffId', id);
			} else {
				this.$store.commit('commit_businessmanId', scene);
				this.relationshipBusinessman(scene);
			}
		}

		// #endif
		this.show_goods_price = this.isLogin ? 5 : this.baseSet.goodsPrice;
		// 实时定位
		if (JSON.stringify(this.$store.state.locationObj) !== '{}') {
			//await this.resetGetLocation();
		}
		// #ifdef APP-PLUS
		// 获取APP版本
		await this.getVersion();
		// #endif
		await this.getBasicField();
		await this.getIndexData();
		await this.getClassSettingInfo();
		// #ifdef MP-WEIXIN
		// 小程序的原生菜单中显示分享按钮
		uni.showShareMenu({
			withShareTicket: false,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// #endif
	},
	methods: {
		switchStore() {
			uni.navigateTo({
				url: '/pagesT/store/ChangeStore'
			});
		},
		// #ifdef MP
		// 添加分销上下级关系 source: 1:首次点击链接 2:首次下单 3:首次付款'
		async relationshipBusinessman(businessmanId) {
			console.log('上级ID', businessmanId);
			if (!this.isLogin) {
				// 没有登录不请求接口
				return;
			}
			await this.$u.api.relationshipBusinessman({
				businessmanId: businessmanId,
				source: 1
			});

			console.log('上下:', data.data);
		},
		// #endif
		// #ifdef APP-PLUS
		// app 升级
		downloadApp() {
			this.closeUPop();
			let url;
			if (this.$common.source() === 2) {
				this.up_show = true;
				url = '';
				const downloadTask = uni.downloadFile({
					url: url,
					success: downloadResult => {
						if (downloadResult.statusCode === 200) {
							plus.runtime.install(
								downloadResult.tempFilePath,
								{
									force: false
								},
								function () {
									console.log('install success...');
									plus.runtime.restart();
								},
								function (e) {
									console.log(e);
									// console.error('install fail...');
								}
							);
						}
					}
				});
				downloadTask.onProgressUpdate(res => {
					this.up_percent = res.progress;
				});
			} else {
				plus.runtime.openURL(this.downloadUrl);
			}
		},
		// 获取app版本 升级
		async getVersion() {
			await this.$u.api
				.getVersion({
					oldVersion: this.oldVersion
				})
				.then(res => {
					uni.setStorageSync('isUpdate', res.data.isUpdate);
					if (res.data.isUpdate) {
						this.downloadUrl = res.data.downloadUrl;
						// App 升级机制，检测安卓
						if (this.$common.source() === 2) {
							this.upgradePop = true;
						} else {
							// IOS 审核通过后再打开升级提示
							if (this.iosAuditStatus === 5) {
								this.upgradePop = true;
							}
						}
					}
				});
		},
		closeUPop() {
			this.upgradePop = false;
		},
		// #endif
		resetGetLocation() {
			this.amapPlugin.getRegeo({
				success: data => {
					const proCity = ['北京市', '天津市', '上海市', '重庆市'];
					// console.log('获取定位:', data)
					const provinceName = data[0].regeocodeData.addressComponent.province;
					const cityName = proCity.includes(provinceName) ? provinceName : data[0].regeocodeData.addressComponent.city;
					const districtName = data[0].regeocodeData.addressComponent.district;
					const address = data[0].desc || data[0].name || data[0].regeocodeData.addressComponent.streetNumber.street || data[0].regeocodeData.addressComponent.township;

					const location = {
						provinceName: provinceName,
						cityName: cityName,
						districtName: districtName,
						address: address
					};
					if (location.districtName !== this.$store.state.locationObj.districtName) {
						uni.showModal({
							title: '提示',
							content: '检测到您位置已改变，是否切换到新的位置',
							success: res => {
								if (res.confirm) {
									this.$store.commit('commit_locationObj', {
										...location,
										latitude: data[0].latitude,
										longitude: data[0].longitude
									});
								}
							}
						});
					}
				},
				fail: err => {
					console.log('获取位置失败：：', err);
				}
			});
		},
		openLocation() {
			console.log('test');
			// #ifdef MP-WEIXIN
			uni.chooseLocation({
				success: res => {
					console.log('test11111');
					const location = this.$_utils.getArea(res.address);
					this.$store.commit('commit_locationObj', {
						...location,
						address: location.address || res.name,
						latitude: res.latitude,
						longitude: res.longitude
					});
				},
				fail: err => {
					console.log('获取位置失败：：', err);
				}
			});
			// #endif
			// #ifdef APP-PLUS || MP-TOUTIAO
			uni.navigateTo({
				url: '/pages/index/SearchAddress'
			});
			// #endif
		},
		async getIndexData() {
			if (getToken()) {
				await this.getCustomerInfo();
				await this.getCartByUserCenterId();
			}
		},

		//首页
		async getTemplate() {
			await this.$u.api
				.homePage({
					pageType: 1
				})
				.then(({ data }) => {
					uni.stopPullDownRefresh();
					this.is_data = true;
					this.model = data.type;
					if (data.type === 2) {
						this.temData = data.data;
						this.topData = data.data[0].modelData;
					} else {
						const homeObj = {};
						for (let i in data.data) {
							const item = data.data[i];
							homeObj[item.moduleAlias] = item;
						}
						this.home_data = homeObj;
						this.cateOn = this.home_data.goodsCate.moduleData.cateData[0].categoryName;
						this.goodsData = this.home_data.goodsCate.moduleData.cateData[0].goodsData;
					}
				});
		},
		//获取购物车数据
		async getCartByUserCenterId() {
			await this.$u.api.getCartByUserCenterId().then(data => {
				this.$store.commit('commit_cartNum', data.data.goodsNum);
				this.$store.commit('commit_cartPrice', data.data.totalMoney);
			});
		},
		// 获取分类页面模版
		async getClassSettingInfo() {
			await this.$u.api.getClassSettingInfo().then(data => {
				this.$store.commit('commit_cateModel', data.data.value);
			});
		},
		// 获取商城基本设置
		async getBasicField() {
			// personnelReview，客户审核,
			// finishData: 4,  完善资料 4禁用 5启用
			// finishDataGo: false,  完善资料登录后立即去完善
			// shop，商城名称，
			// images，商城LOGO，
			// goodsPrice，商品价格是否允许游客查看，
			// stockDisplay，库存展示设置，4:不显示库存；5: 显示有/无货；6:显示库存数量
			// themeStyle，风格设置
			// startUpPage，启动页设置
			// startDeliveryPrice，起送价
			// freeExpressPrice 满多少元包邮
			// isSalesNum，是否显示销量，4：不显示，5:显示
			// cancelOrder，5开启：订单在出库前客户可以点击取消订单按钮；4禁用：只有待审核的订单客户才能操作取消订单按钮；
			// cancelOrderAudit，取消订单审核状态 5开启 4禁用

			await this.$u.api
				.getBasicField({
					field: [
						'personnelReview',
						'finishData',
						'finishDataGo',
						'shop',
						'images',
						'goodsPrice',
						'stockDisplay',
						'themeStyle',
						'startUpPage',
						'startDeliveryPrice',
						'freeExpressPrice',
						'isSalesNum',
						'phone',
						'cancelOrder',
						'cancelOrderAudit'
					]
				})
				.then(data => {
					this.show_goods_price = this.isLogin ? 5 : data.data.goodsPrice;
					this.startUpPage = data.data.startUpPage || {
						img: '',
						isEnable: false,
						time: 5
					};
					let themeStyle = '';
					if (data.data.themeStyle) {
						let theme = data.data.themeStyle.theme;
						if (!theme) {
							switch (data.data.themeStyle.label) {
								case '纯净绿':
									theme = 'green';
									break;
								case '热情红':
									theme = 'red';
									break;
								case '活力橙':
									theme = 'orange';
									break;
								case '格调金':
									theme = 'gold';
									break;
								case '雅致粉':
									theme = 'pink';
									break;
								case '商务蓝':
									theme = 'blue';
									break;
							}
						}
						themeStyle = {
							...data.data.themeStyle,
							theme: theme
						};
					}
					this.$store.commit('commit_baseSet', {
						...data.data,
						isSalesNum: data.data.isSalesNum || 5,
						preSale: data.data.preSale || 4,
						startDeliveryPrice: data.data.startDeliveryPrice || 0,
						themeStyle: themeStyle || {
							label: '热情红',
							theme: 'red',
							color_t: '#ff3883',
							color_o: '#fd463e'
						},
						startUpPage: data.data.startUpPage || {
							img: '',
							isEnable: false,
							time: 5
						}
					});
				});
		},
		//先获取个人资料 用来判断审核状态
		async getCustomerInfo() {
			await this.$u.api.getCustomerInfo().then(({ data }) => {
				this.$store.commit('commit_userStatus', data);
				if (this.baseSet.finishDataGo && data.status === 0) {
					this.tip_model = true;
				}
			});
		},
		async getEnterpriseInfo() {
			await this.$u.api.getEnterpriseInfo().then(({ data }) => {
				this.$store.commit('commit_iosAuditStatus', data.iosAuditStatus);
				this.$store.commit('commit_enterpriseInfo', data);
				if (new Date().getTime() >= data.expireTime * 1000) {
					uni.reLaunch({
						url: '/pages/index/FullScreen'
					});
				}
			});
		},
		// 完善资料提示取消
		tipCancel() {
			this.tip_model = false;
		},
		// 跳转完善资料页面
		finishCofirm() {
			this.goPage('/pagesT/user/editUserInfo');
		}
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.getTemplate();
		this.getIndexData();
		this.getBasicField();
		this.getClassSettingInfo();
	},
	onPageScroll(obj) {
		this.scrollTop = obj.scrollTop;
	}
};
</script>
<style lang="scss" scoped>
.view-wrap {
	background-repeat: no-repeat;
	background-color: #f7f8fa;
	background-size: 750rpx;
	// background-position: 0 calc(var(--status-bar-height) + 44px);
}

.upgrade-view {
	background-color: #fff;
	text-align: center;
	width: 600upx;
	border-radius: 12upx;
	padding: 24upx;
	position: relative;

	.closePop {
		position: absolute;
		bottom: -100upx;
		width: 50upx;
		height: 50upx;
		color: #fff;
		left: 50%;
		transform: translateX(-25upx);

		.ibonguanbi {
			font-size: 48upx;
		}
	}

	.upgrade-img {
		width: 275upx;
		height: 275upx;
		margin: 30upx auto 0;
		display: block;
	}

	.upgrade-tit {
		font-size: 36upx;
	}

	.upgrade-num {
		color: #999;
		font-size: 24upx;
		padding: 20upx;
	}

	.upgrade-cont {
		font-size: 28upx;
		padding-bottom: 30upx;
		line-height: 36upx;
	}

	.upgrade-btn {
		width: 516upx;
		height: 86upx;
		font-size: 32upx;
		color: #fff;
		border-radius: 8upx;
		background-color: #007aff;
		line-height: 86upx;
		margin: 0 auto;
	}
}
</style>
